// @/store/auth.js
import { defineStore } from 'pinia'
import { login as apiLogin, register as apiRegister, changePassword as apiChangePassword, getPermissions } from '@/api/auth'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    token: localStorage.getItem('token') || '',
    user: JSON.parse(localStorage.getItem('user') || '{}'),
    roles: JSON.parse(localStorage.getItem('roles') || '[]'),
    permissions: JSON.parse(localStorage.getItem('permissions') || '[]')
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    userRoles: (state) => state.roles,
    userPermissions: (state) => state.permissions,
    isSuperAdmin: (state) => state.roles.includes('ROLE_SUPER_ADMIN'),
    isAdmin: (state) => state.roles.includes('ROLE_ADMIN') || state.roles.includes('ROLE_SUPER_ADMIN'),
    userInfo: (state) => state.user,
    
    // 新增权限检查方法
    hasPermission: (state) => (requiredPermissions) => {
      if (!requiredPermissions || requiredPermissions.length === 0) return true
      // if (state.isSuperAdmin) return true // 超级管理员拥有所有权限
      return requiredPermissions.some(perm => state.permissions.includes(perm))
    }
  },
  
  actions: {
    async login(credentials) {
      try {
        const response = await apiLogin(credentials)
        this.setAuth(response)
        await this.loadPermissions() // 登录后加载权限
        return response
      } catch (error) {
        throw error
      }
    },
    
    async register(userData) {
      try {
        const response = await apiRegister(userData)
        return response
      } catch (error) {
        throw error
      }
    },
    
    async changePassword(passwordData) {
      try {
        const response = await apiChangePassword(passwordData)
        return response
      } catch (error) {
        throw error
      }
    },
    
    async loadPermissions() {
      try {
        const perms = await getPermissions()
        this.permissions = perms
        localStorage.setItem('permissions', JSON.stringify(perms))
      } catch (error) {
        console.error('加载权限失败:', error)
        this.permissions = []
      }
    },
    
    setAuth(data) {
      this.token = data.token
      this.user = {
        id: data.id,
        username: data.username,
        email: data.email,
        name: data.name,
        department: data.department
      }
      this.roles = data.roles
      
      localStorage.setItem('token', data.token)
      localStorage.setItem('user', JSON.stringify(this.user))
      localStorage.setItem('roles', JSON.stringify(this.roles))
    },
    
    logout() {
      this.token = ''
      this.user = {}
      this.roles = []
      this.permissions = []
      
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('roles')
      localStorage.removeItem('permissions')
    }
  }
})